//
//  UIColorEx.swift
//  poetry
//
//  Created by daiyunpeng on 2021/12/20.
//

import Foundation
import UIKit

extension UIColor {
    
    public convenience init(hexString: String, alpha: CGFloat = 1.0) {
        
        var hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
        hexString = hexString.lowercased()

        if hexString.hasPrefix("#") {
            hexString = String(hexString.dropFirst())
        }
        if hexString.hasPrefix("0x") {
            hexString = String(hexString.dropFirst(2))
        }
        
        // hex值少于6位，返回白色
        if hexString.count < 6 {
            self.init(red: 255, green: 255, blue: 255, alpha: alpha)
        } else {
            var color:UInt64 = 0
            Scanner(string: hexString).scanHexInt64(&color)
            
            self.init(red: CGFloat((color & 0xFF0000) >> 16) / 255.0,
                      green: CGFloat((color & 0x00FF00) >> 8) / 255.0,
                      blue: CGFloat(color & 0x0000FF) / 255.0,
                      alpha: alpha)
        }
        }
}
